<template>
  <div>
    <div class="pa-4 text-center" style="margin-top:15%;" v-show="!payshow">
      <v-icon size="128" color="warning">{{ icon }}</v-icon>
      <h3 class="title font-weight-light mb-2">{{ title }}</h3>
      <span class="caption grey--text">{{ desc }}</span>
      <v-card
        class="mx-auto"
        color="primary"
        dark
        max-width="100%"
        style="margin-top:15%;"
      >
        <v-card-text style="subtitle-2">
          {{ agencyinfo.order.body }}
        </v-card-text>
        <v-card-text>
          订单号码：{{ agencyinfo.order.order_no }}
        </v-card-text>
        <v-card-actions>
          <v-list-item class="grow">
            <v-list-item-avatar>
              <v-img
                class="elevation-6"
                :src="agencyinfo.head_img"
              ></v-img>
            </v-list-item-avatar>

            <v-list-item-content>
              <v-list-item-title>{{ agencyinfo.name }}</v-list-item-title>
            </v-list-item-content>

            <v-row
              align="center"
              justify="end"
            >
              <span class="subheading mr-2">代付金额</span>
              <span class="mr-1">{{ agencyinfo.order.fee_type }}:</span>
              <span class="subheading">{{ agencyinfo.order.total_fee/100 }}</span>
            </v-row>
          </v-list-item>
        </v-card-actions>
      </v-card>
      <v-btn :disabled="pay.btn.disabled" :loading="pay.btn.loading" v-show="pay.btn.show" @click="paynow" style="margin-top:50px;width:100%" :color="pay.btn.color"> {{ pay.btn.text }} </v-btn>
    </div>
    <div class="pa-4 text-center" style="margin-top:15%;" v-show="payshow">
      <v-icon size="128" :color="iconcolor"> {{ icon }}</v-icon>
      <h3 class="title font-weight-light mb-2">{{ title }}</h3>
      <span class="caption grey--text">{{ desc }}</span>
      <v-btn :disabled="pay.done.disabled" :loading="pay.done.loading" v-show="pay.done.show" @click="done" style="margin-top:50px;width:100%" :color="pay.done.color"> {{ pay.done.text }} </v-btn>
      <v-btn :disabled="pay.btn.disabled" :loading="pay.btn.loading" v-show="pay.btn.show" @click="paynow" style="margin-top:50px;width:100%" :color="pay.btn.color"> {{ pay.btn.text }} </v-btn>
    </div>
  </div>
</template>

<script>
import { domain, OauthWechat, AgencyInfo, OauthCodeToToken } from './../../api/new'
import { wxpayjsapi } from './../../api/api'

const search = (variable) => {
    var arrStr = window.location.search.substring(1).split("&");
    for (var i = 0; i < arrStr.length; i++) {
      var temp = arrStr[i].split("=");
      if (temp[0] === variable){
          return decodeURIComponent(temp[1]);
      }  
    }
    return (false)
}
export default {
  data: ()=>({
    payshow:false,
		icon:'',
    title: '请等待',
    desc: '...',
    iconcolor:'',
    pay:{
      btn:{
        text:'立即支付',
        show:true,
        color:'success',
        loading:true,
        disabled:false
      },
      done:{
        text:'完成支付',
        show:false,
        color:'success',
        loading:false,
        disabled:false
      }
    },
    agencyinfo:{
      name:'',
      head_img:'',
      order:{
        order_no:'',
        total_fee:'',
        fee_type:'',
        body:'',

      }
    }
  }),
  methods:{
    done:function(){
      // this.$router.push(this.$cookies.get('calluri')+'?order_no='+this.$cookies.get("agency_order_no"))
      this.$store.commit('setAlert',{icon:'close',text:'通知对方我已完成付款',show:true})
    },
    paynow:function(){
      if(this.agencyinfo.order.status == 2){
        return
      }
      // 获取jsapi
      this.$store.commit('setProgress',true)
      this.pay.btn.loading = true
      var order_no = this.$cookies.get("agency_order_no")
      const wxPayCall = (res) =>{
          console.log(res)
          if(res.err_msg == "get_brand_wcpay_request:ok" ){
            // res.err_msg 将在用户支付成功后返回ok，但并不保证它绝对可靠。
            fetch(domain+'/api/order/status?order_no='+ this.$cookies.get("agency_order_no")+"&hl="+search("hl"), {
              headers: {
                  'authtoken': this.$cookies.get("authtoken"),
              },
              method: 'POST', // *GET, POST, PUT, DELETE, etc.
              mode: 'cors', // no-cors, cors, *same-origin
              redirect: 'follow', // manual, *follow, error
              referrer: 'no-referrer', // *client, no-referrer
            })
            .then((res)=> res.json())
            .then((res)=>{
              if(res.code==1){
                // 支付结果
                this.title = "成功"
                this.desc = ''
                this.icon = 'check_circle'; this.iconcolor='success'
                this.pay.btn.show = false
                this.pay.done = {
                  text:'完成支付',
                  show:true,
                  color:'success',
                  loading:false,
                  disabled:false
                }
              }else{
                this.icon = 'error'; this.iconcolor='error'
                this.title = "支付失败"
                this.desc = ''
              }
              this.$store.commit('setAlert',{icon:'close',text: res.msg,show:true})
              this.$store.commit('setProgress',false)
              this.title = res.msg
              this.payshow = true

            })
            .catch((err)=>{
              this.payshow = true
              this.title = err
              this.$store.commit('setAlert',{icon:'close',text:err,show:true})
              this.$store.commit('setProgress',false)
              this.icon = 'error'; this.iconcolor='error'
              this.desc = ''
              // this.icon = 'check_circle'; this.iconcolor='success'
              this.desc = '检查订单状态错误，您可以进入订单列表查看订单状态'
              this.pay.btn = {
                text:'检查订单状态错误',
                show:true,
                color:'success',
                loading:false,
                disabled:true
              }
            })
          }else{
            this.icon = 'error'; this.iconcolor='error'
            this.title = "支付失败"
            this.desc = ''
            this.$store.commit('setAlert',{icon:'close',text:'支付失败',show:true})
            this.$store.commit('setProgress',false)
            this.icon = 'error'; this.iconcolor='error'
            this.pay.btn = {
              text:'重新支付',
              show:true,
              color:'success',
              loading:false,
              disabled:false
            }
          }
        }
      wxpayjsapi(order_no,this.$cookies.get("authtoken"))
      .then((resp)=>{
        var res = resp.data
        if(res.code == 1){
          function onBridgeReady(){
            WeixinJSBridge.invoke(
              'getBrandWCPayRequest', {
                "appId":res.data.AppID,     //公众号名称，由商户传入     
                "timeStamp":""+res.data.Timestamp,        //时间戳，自1970年以来的秒数     
                "nonceStr": res.data.NonceStr, //随机串     
                "package":res.data.Package,     
                "signType": res.data.SignType,      //微信签名方式：     
                "paySign": res.data.Sign, //微信签名 
              },
              function(res){
                wxPayCall(res)
              }
              ); 
            }
            if(typeof WeixinJSBridge == "undefined"){
                if( document.addEventListener ){
                  document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                }else if (document.attachEvent){
                  document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
                  document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            }else{
              onBridgeReady();
            }
        }
        this.icon = 'error'; this.iconcolor='error'
        this.desc = ''
        this.title = res.msg
        this.$store.commit('setAlert',{icon:'close',text:res.msg,show:true})
        this.$store.commit('setProgress',false)
        this.pay.btn.loading = false
      })
      .catch((err)=>{
        this.icon = 'error'; this.iconcolor='error'
        this.desc = ''
        this.title = res.err
        this.$store.commit('setAlert',{icon:'close',text:err,show:true})
        this.$store.commit('setProgress',false)
        this.pay.btn.loading = false
      })
    }
  },
	created:function(){
    var authtoken = this.$cookies.get("authtoken")
    var order_no = search("order_no")
    if(order_no){
      this.$cookies.set("agency_order_no",order_no)
    }
    if(search('calluri')){
      this.$cookies.set('calluri',search('calluri'))
    }
    if(!this.$cookies.get("agency_order_no")){ // 没有订单号码
      this.icon = 'error'
      this.title = '没有需要支付的订单'
      this.desc = ''
      this.pay.btn.disabled = true
      this.$store.commit('setAlert',{icon:'close',text:'没有需要支付的订单',show:true})
      this.$store.commit('setProgress',false)
      return
    }
    if(authtoken != undefined ){ // 已经登陆的情况下
      // 获取代理支付的订单信息
      AgencyInfo(this.$cookies.get("agency_order_no"))
      .then((resp)=>{
        var res = resp.data
        if(res.code == 1){
          this.agencyinfo = res.data
          this.title = "代付请求"
          this.desc = "手机号码为"+res.data.phone+"的用户，向您发起了代付请求,请核实身份后再支付！"
          if(res.data.order.status == 2){
            this.pay.btn.text = '此订单已被支付'
            this.pay.btn.show = true
            this.pay.btn.color = 'error'
            this.pay.btn.disabled = true
          }
        }
        this.$store.commit('setAlert',{icon:'close',text:res.msg,show:true})
        this.$store.commit('setProgress',false)
        this.pay.btn.loading = false
      })
      .catch((err)=>{
        this.$store.commit('setAlert',{icon:'close',text:err,show:true})
        this.$store.commit('setProgress',false)
         this.pay.btn.loading = false
      })
      // return
    }
    if(search("code")){ // 使用 code 兑换 authtoken
      OauthCodeToToken(search("code"))
      .then((resp)=>{
        var res = resp.data
        if(res == 1){
          this.$cookies.set("authtoken", res.data, 1800) 
        }
        this.$store.commit('setAlert',{icon:'close',text:res.msg,show:true})
        this.$store.commit('setProgress',false)
      })
      .catch((err)=>{
        this.$store.commit('setAlert',{icon:'close',text:err,show:true})
        this.$store.commit('setProgress',false)
      })
    }else{
      OauthWechat('agency')
      .then((resp)=>{
        var res = resp.data
        if( res.code == 1 ){
          window.location.href = res.data.uri
        }
        this.$store.commit('setAlert',{icon:'close',text:"正在前往授权",show:true})
        this.$store.commit('setProgress',false)
      })
      .catch((err)=>{
        this.$store.commit('setAlert',{icon:'close',text:err,show:true})
        this.$store.commit('setProgress',false)
      })
    }
    
	},
}
</script>

<style>

</style>